package com.eliza.module

import android.content.Context
import android.util.Log
import androidx.work.Worker
import androidx.work.WorkerParameters
import androidx.work.workDataOf
import java.io.File
import kotlin.random.Random

class InfiniteWorker(context: Context, workerParams: WorkerParameters) :
    Worker(context, workerParams) {
    override fun doWork(): Result {

        try {
            val i = Random.nextInt() / Random.nextInt(1)
            Log.e("InfiniteWorker", "working")
            return Result.success(workDataOf("result" to i))
        } catch (e: InterruptedException) {
            Log.e("InfiniteWorker", "failure")
            return Result.failure()
        }
    }

    override fun onStopped() {
        super.onStopped()
        Log.e("InfiniteWorker", "work stop")

    }
}

class TestWorker(context: Context, workerParams: WorkerParameters) : Worker(context, workerParams) {
    override fun doWork(): Result {
        Log.e("TestWorker", "Result.success")
        return Result.success()
    }

    override fun onStopped() {
        super.onStopped()
        Log.e("TestWorker", "work stop")

    }
}

class TestFileWorker(context: Context, workerParams: WorkerParameters) :
    Worker(context, workerParams) {
    override fun doWork(): Result {
        val isCreate = inputData.getInt("KEY", 1)
        val outputDirectory = File(applicationContext.filesDir, "work.txt")
        if (outputDirectory.exists()) {
            when (isCreate) {
                0 -> {
                    val createNewFile = outputDirectory.createNewFile()
                    Log.i("TestFileWorker", "create $createNewFile")

                }
                else -> {
                    val entries = outputDirectory.listFiles()
                    if (entries != null) {
                        for (entry in entries) {
                            val name = entry.name
                            if (name.isNotEmpty() && name.endsWith("work.txt")) {
                                val deleted = entry.delete()
                                Log.i("TestFileWorker", "Deleted $name - $deleted")
                            }
                        }
                    }
                }
            }
        }

        Log.e("TestWorker", "Result.success")
        return Result.success()
    }

    override fun onStopped() {
        super.onStopped()
        Log.e("TestWorker", "work stop")

    }
}
